<script setup lang="ts">
import { reactive } from "vue";
import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";

import ByPage from "@/components/ui/ByPage.vue";
import ByButton from "@/components/ui/ByButton.vue";
import ViewList from "@/components/common/ViewList.vue";
import ByCheckbox from "@/components/ui/ByCheckbox.vue";
import CouponItem from "@/pages/coupon/components/CouponItem.vue";

import ApiTicket from "@/api/ticket";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";

const seleceted = reactive(new Set<{ act_id: number; sn: string }>());

const { loading, list, nextPage, resetToFirst } = useList<any>(
  ApiTicket.userTicketList,
  {
    immediate: false,
    search: { status: 1 },
  }
);

useDidShow(() => resetToFirst());
useReachBottom(() => nextPage());

// 转赠提交
const { loading: submitLoading, run } = useFetch(ApiTicket.userTicketShare, {
  immediate: false,
  onSuccess(res: any) {
    const [first] = seleceted;
    Taro.navigateTo({
      url: `share?batchNum=${res.batch_num}&actId=${first.act_id}`,
    });
  },
});

const handleSubmit = async () => {
  const { confirm } = await Taro.showModal({
    title: "转赠确认",
    confirmText: "确定转赠",
  });

  if (confirm) run({ sns: [...seleceted].map((e) => e.sn).join(",") });
};

//
const handleSelected = (item) => {
  seleceted.has(item) ? seleceted.delete(item) : seleceted.add(item);
};
</script>

<template>
  <ByPage footer-fixed footer-safe>
    <template #footer>
      <view class="my-3 text-center" v-if="list.length > 0">
        <ByButton
          class="w-1/2 bg-dark"
          :loading="submitLoading"
          :disabled="seleceted.size == 0"
          @tap="handleSubmit"
          >转赠 ({{ seleceted.size }})</ByButton
        >
      </view>
    </template>

    <ViewList :loading="loading" :is-empty="list.length == 0">
      <template v-for="item in list" :key="item.id">
        <view class="flex items-center mx-3 my-4">
          <view class="flex-none mr-3">
            <ByCheckbox
              :model-value="seleceted.has(item)"
              @change="handleSelected(item)"
            />
          </view>

          <view class="flex-auto min-w-0">
            <CouponItem selection :source="item" @tap="handleSelected(item)" />
          </view>
        </view>
      </template>
    </ViewList>
  </ByPage>
</template>

<style lang="less">
/* 使用伪元素创建固定背景 */
page::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #fef7ee, #dec2a0);
  z-index: -1; /* 确保背景在内容下方 */
}
</style>
